<?php
namespace app\admin\Controller;
class Company extends Common {

	/*
	*	构造函数
	*/
	function __construct(){
		parent::__construct();
	}

	public function index(){
		$pageParam = ['query'=>[]];
		$where = [];
		$keyword = input('keyword');
		if($keyword != ''){
			$where['name'] = array('like','%'.$keyword.'%');
			$pageParam['query']['keyword'] = $keyword;
		}

		$company_result = db('xls_company')->where($where)->paginate(20, false, $pageParam)->each(function($item,$key){
			$province_result = db('area')->where(array('id'=>$item['province']))->field('name')->find();
			$city_result = db('area')->where(array('id'=>$item['city']))->field('name')->find();
			$area_result = db('area')->where(array('id'=>$item['area']))->field('name')->find();
			$item['province'] = $province_result['name'];
			$item['city'] = $city_result['name'];
			$item['area'] = $area_result['name'];
			return $item;
		});
		$num = db('xls_company')->count();


		if(input('export')){
			$this->export();exit;
		}

		$page = $company_result->render();
		$this->assign('company_result',$company_result);
		$this->assign('keyword',$keyword);
		$this->assign('page',$page);
		return 	$this->fetch();
	}

	public function export()
	{
		ini_set('memory_limit','4072M');
		set_time_limit ( 0 );

		$headArr = array("ID","企业名","企业地址");

		$fileName='企业列表.csv';

		vendor("Excel.PHPExcel");
		$cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
		$cacheSettings = array('memoryCacheSize'=>'16MB');
		\PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
		//创建新的PHPExcel对象
		$objPHPExcel = new \PHPExcel();
		$objProps = $objPHPExcel->getProperties();

		//设置表头
		$key = ord("A");
		foreach ($headArr as $v) {
			$colum = chr($key);
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
			$key += 1;
		}

		$column = 2;
		$objActSheet = $objPHPExcel->getActiveSheet();

		$total_num = db('xls_company')->count();
		$pre_num = 500;
		for($i=0;$i<intval($total_num/$pre_num)+1;$i++){
			$star = $i * $pre_num;
			$list = db('xls_company')->limit($star, $pre_num)->select();
			$data = [];
			foreach($list as $k => $v){
				$data[$k][] = $v['id'];
				$data[$k][] = $v['name'];

				$province_result = db('area')->where(array('id'=>$v['province']))->field('name')->find();
				$city_result = db('area')->where(array('id'=>$v['city']))->field('name')->find();
				$area_result = db('area')->where(array('id'=>$v['area']))->field('name')->find();
				$data[$k]['dizhi'] = $province_result['name'].$city_result['name'].$area_result['name'];
			}
			foreach ($data as $key => $rows) { //行写入
				$span = ord("A");
				foreach ($rows as $keyName => $value) {// 列写入
					$j = chr($span);
					$objActSheet->setCellValue($j . $column, $value);
					$span++;
				}
				$column++;
			}
			unset($list);
			unset($data);
			ob_flush();
			flush();
			usleep(2000);
		}


		$fileName = iconv("utf-8", "gb2312", $fileName);
		//重命名表
		$objPHPExcel->getActiveSheet()->setTitle('Simple');
		//设置活动单指数到第一个表,所以Excel打开这是第一个表
		$objPHPExcel->setActiveSheetIndex(0);
		//将输出重定向到一个客户端web浏览器(Excel2007)
		ob_end_clean();//清除缓冲区,避免乱码
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-type: application/vnd.ms-excel');
		header("Content-Disposition: attachment; filename=\"$fileName\"");
		header('Cache-Control: max-age=0');
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		/*$filePath = '/tmp/' . rand(0, getrandmax()) . rand(0, getrandmax()) . ".tmp";
        $objWriter->save($filePath);
        readfile($filePath);
        unlink($filePath);*/
		$objWriter->save('php://output'); //文件通过浏览器下载
		die;
	}
}